#pragma once

/*
 * KV存储服务器状态机
 */

#include <string>

#include "SkipList.h"
#include "state_machine/StateMachine.h"

class KVStateMachine : public raft::state_machine::StateMachine {
public:
    KVStateMachine();

    // 处理日志条目
    bool apply(std::shared_ptr<raft::utils::Command> &command, std::string *msg) override;

    // 中间件查询层
    grpc::Status execute_command(grpc::ServerContext *context,
                                 const middleware_rpc_proto::ExecuteCommand *request,
                                 middleware_rpc_proto::ExecuteCommandReply *reply) override;

    // 生成快照
    std::string snapshot() override;

    // 从快照恢复
    void restore(const std::string &snapshot) override;

private:
    // 处理插入操作
    bool insert_element(const std::string &key, const std::string &value, std::string *msg);

    // 处理删除操作
    bool delete_element(const std::string &key, std::string *msg);

    // 处理查找操作
    bool search_element(const std::string &key, std::string *msg);

    // 处理设置操作
    bool set_element(const std::string &key, const std::string &value);

    // 跳表
    skip_list::SkipList<std::string, std::string> skip_list_;
};